/*********************************************
 * Student    : Teodoro Cipresso
 * Course     : CS286
 * Professor  : Vidya Setlur
 * Assignment : Term Project (BlueTanks)
 *********************************************/
package edu.sjsu.cs286.teodoro.cipresso.wizard;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.List;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;

import edu.sjsu.cs286.teodoro.cipresso.bluetooth.BlueTankConnectionManager;
import edu.sjsu.cs286.teodoro.cipresso.bluetooth.BlueTankGameStatusScreen;
import edu.sjsu.cs286.teodoro.cipresso.playfield.BlueTankGameCanvas;
import edu.sjsu.cs286.teodoro.cipresso.playfield.BlueTankMIDlet;
import edu.sjsu.cs286.teodoro.cipresso.sound.BlueTankSoundHolder;
import edu.sjsu.cs286.teodoro.cipresso.sprites.BlueTankImageHolder;
import edu.sjsu.cs286.teodoro.cipresso.sprites.BlueTankVehicleSprite;
import edu.sjsu.cs286.teodoro.cipresso.sprites.IBlueTankSprite;

/**
 * This class implements the game welcome screen. The user selects his/her
 * ownerTank. Two or more ownerTank colors will made available for selection.
 * The user should not be allowed to begin the game if both players have
 * selected an identical ownerTank.
 */
public class BlueTankGameContainer implements CommandListener,
		IBlueTankGameContainer, IBlueTankSprite {

	public static int soundEffectVolumeLevel = 30;

	public static int musicVolumeLevel = 40;

	private BlueTankMIDlet midlet = null;

	private List tankSelectList = null;

	private BlueTankGameCanvas btCanvas;

	private BlueTankConnectionManager btManager;

	private BlueTankGameStatusScreen statScr;

	private Command exitCmd = new Command("Exit", Command.EXIT, 10);

	private Command selectCmd = new Command("Select", Command.ITEM, 1);

	/**
	 * Default constructor
	 * 
	 * @param parent,
	 *            the containing midlet
	 */
	public BlueTankGameContainer(BlueTankMIDlet parent) {
		midlet = parent;
		//
		statScr = new BlueTankGameStatusScreen(midlet);
		btCanvas = new BlueTankGameCanvas(this);
		//
	} // BlueTankGameContainer()

	/**
	 * This method shows the screens and menus that allow for setting up a new
	 * game between two devices. The sequence is as follows (1) Show the game
	 * welcome screen (2) Allow the devices to get connected (3) Ask the user to
	 * pick a tank, making sure the selections are unique (4) start the game.
	 */
	public void setupNewGame() {
		// play game music loop during game setup
		Player gameLoop = null;
		try {
			gameLoop = BlueTankSoundHolder.getGameMusicLoopPlayer();
			gameLoop.setLoopCount(-1);
			gameLoop.start();
		} catch (MediaException e) {
			e.printStackTrace();
		}
		// create connection manager
		btManager = new BlueTankConnectionManager(this);
		// wait till we get connected
		while (!btManager.isConnected()) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
			}
		}
		//
		Display.getDisplay(midlet).setCurrent(createSelectTankScreen());
		// wait till user chooses a ownerTank
		while (btCanvas.getSelfTank() == null) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
			}
		}
		//
		Display.getDisplay(midlet).setCurrent(statScr);
		//
		statScr.clearStatusMessages();
		statScr.setPaintTankSelections(true);
		// wait till peer selects ownerTank
		while (btCanvas.getPeerTank() == null) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
			}
		}
		statScr.forceRepaint();
		// display prepare for battle screen
		try {
			Thread.sleep(4000);
		} catch (InterruptedException e) {
		}
		// we're ready to go
		btCanvas.start();
		Display.getDisplay(midlet).setCurrent(btCanvas);
	} // setupNewGame()

	/**
	 * This method creates the screen that shows that tanks for selection
	 */
	public List createSelectTankScreen() {
		// create screen object
		tankSelectList = new List(SCREEN_TITLE, List.IMPLICIT);
		// create list item elements
		tankSelectList.append(BLUE_TANK_NAME, BlueTankImageHolder
				.getTankSelectImageByName(BLUE_TANK_NAME));
		tankSelectList.append(GREEN_TANK_NAME, BlueTankImageHolder
				.getTankSelectImageByName(GREEN_TANK_NAME));
		tankSelectList.append(RED_TANK_NAME, BlueTankImageHolder
				.getTankSelectImageByName(RED_TANK_NAME));
		tankSelectList.append(YELLOW_TANK_NAME, BlueTankImageHolder
				.getTankSelectImageByName(YELLOW_TANK_NAME));
		// create commands
		tankSelectList.addCommand(exitCmd);
		tankSelectList.addCommand(selectCmd);
		tankSelectList.setCommandListener(this);
		// return
		return tankSelectList;
	} // createSelectTankScreen()

	/**
	 * This method implements the softkey actions. If the peer has already
	 * selected a tank that this user is attempting to select, and error is
	 * displayed.
	 */
	public void commandAction(Command c, Displayable s) {
		if (c.getLabel().equals(exitCmd.getLabel())) {
			//
			midlet.destroyApp(true);
		} else if (c.getLabel().equals(selectCmd.getLabel())) {
			try {
				//
				String selected = tankSelectList.getString(tankSelectList
						.getSelectedIndex());
				// add self ownerTank if peer hasn't already selected it
				BlueTankVehicleSprite tank = btCanvas.getPeerTank();
				String peerTankName = (tank != null) ? tank.getTankName()
						: null;
				if ((peerTankName != null && !peerTankName
						.equalsIgnoreCase(selected))
						|| peerTankName == null) {
					setSelfTankByName(selected);
				} else {
					Alert alert = new Alert("Tank Selection Failed",
							"Your Opponent Has Already Selected This Tank.",
							null, AlertType.ERROR);
					alert.setTimeout(3000);
					Display.getDisplay(midlet).setCurrent(alert);
				}
				//
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	} // commandAction()

	/**
	 * Process the selection of this clients tank
	 * 
	 * @param tankName,
	 *            the tank name constant from IBlueTankSprite
	 */
	public void setSelfTankByName(String tankName) {
		//
		Image image = null;
		int rgb = 0;
		//
		if (tankName.equals(BLUE_TANK_NAME)) {
			image = BlueTankImageHolder.getBlueTank();
			rgb = BLUE_TANK_COLOR;
		} else if (tankName.equals(GREEN_TANK_NAME)) {
			image = BlueTankImageHolder.getGreenTank();
			rgb = GREEN_TANK_COLOR;
		} else if (tankName.equals(YELLOW_TANK_NAME)) {
			image = BlueTankImageHolder.getYellowTank();
			rgb = YELLOW_TANK_COLOR;
		} else if (tankName.equals(RED_TANK_NAME)) {
			image = BlueTankImageHolder.getRedTank();
			rgb = RED_TANK_COLOR;
		}
		//
		getBtCanvas().setSelfTank(image, rgb, tankName);
		// Notify Peer
		btManager.getBtMessageHandler().sendTankSelectNotify(tankName);
		//
	} // setSelfTankByName()

	/**
	 * Process the selection of the peer tank, this method is called from the
	 * BlueTankMessageHandler instance when a message is received from the peer.
	 * 
	 * @param tankName,
	 *            the tank name constant from IBlueTankSprite
	 */
	public void setPeerTankByName(String tankName) {
		//
		Image image = null;
		int rgb = 0;
		//
		if (tankName.equals(BLUE_TANK_NAME)) {
			image = BlueTankImageHolder.getBlueTank();
			rgb = BLUE_TANK_COLOR;
		} else if (tankName.equals(GREEN_TANK_NAME)) {
			image = BlueTankImageHolder.getGreenTank();
			rgb = GREEN_TANK_COLOR;
		} else if (tankName.equals(YELLOW_TANK_NAME)) {
			image = BlueTankImageHolder.getYellowTank();
			rgb = YELLOW_TANK_COLOR;
		} else if (tankName.equals(RED_TANK_NAME)) {
			image = BlueTankImageHolder.getRedTank();
			rgb = RED_TANK_COLOR;
		}
		//			
		btCanvas.setPeerTank(image, rgb, tankName);
		//
	} // setPeerTankByName()

	/**
	 * Getter for game canvas instance
	 * 
	 * @return the BlueTankGameCanvas instance
	 */
	public BlueTankGameCanvas getBtCanvas() {
		return btCanvas;
	}

	/**
	 * Getter for the message handler instance
	 * 
	 * @return the BlueTankMessage handler instance
	 */
	public BlueTankConnectionManager getBtManager() {
		return btManager;
	}

	/**
	 * Getter for the game status screen
	 * 
	 * @return the BlueTankGameStatusScreen instance
	 */
	public BlueTankGameStatusScreen getStatScreen() {
		return statScr;
	} // getStatScreen()

	/**
	 * @return the desired sound effect volume level
	 */
	public static int getSoundEffectVolumeLevel() {
		return soundEffectVolumeLevel;
	} // getSoundEffectVolumeLevel()

	/**
	 * @param the
	 *            sound effect volume
	 */
	public static void setSoundEffectVolumeLevel(int volumeLevel) {
		BlueTankGameContainer.soundEffectVolumeLevel = volumeLevel;
	} // setSoundEffectVolumeLevel()

	/**
	 * @return the music volume
	 */
	public static int getMusicVolumeLevel() {
		return musicVolumeLevel;
	} // getMusicVolumeLevel()

	/**
	 * @return the desired music volume level
	 */
	public static void setMusicVolumeLevel(int musicVolumeLevel) {
		BlueTankGameContainer.musicVolumeLevel = musicVolumeLevel;
	} // setMusicVolumeLevel()

	/**
	 */
	public void update() {
		// not implemented
	} // update()

	/**
	 * @return the containing game midlet
	 */
	public BlueTankMIDlet getMidlet() {
		return midlet;
	} // getMidlet()

} // BlueTankGameContainer()
